package gom.example.gramediamajalah;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.widget.Toast;

public class AmbilData extends Activity {
	 String serverURL ="http://192.168.2.23/codeigniter-restserver-master/index.php/gom/articles";
		@Override
	    public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.ambildata); 
	        GetJsonTask jsontask = new GetJsonTask();
	        jsontask.execute(" ");
//	        InputStream article = AmbilArticle(serverURL);
//	        String hasil = rubahKeString(article);
//	        Toast pesan = Toast.makeText(this, hasil, Toast.LENGTH_LONG);
//	        pesan.setGravity(Gravity.TOP,0,20);
//	        pesan.show();
//	        
	 }

	private class GetJsonTask extends AsyncTask<String, Void, String > {

		@Override
		protected String doInBackground(String... URL) {
			 InputStream article = AmbilArticle(serverURL);
		       
				String jsontext;
			jsontext =rubahKeString(article);
				return jsontext;
		}

			@Override
		protected void onPostExecute(String result) {
			Toast.makeText(AmbilData.this, result, Toast.LENGTH_LONG).show() ;
				// TODO Auto-generated method stub
				super.onPostExecute(result);
			}

		@Override
			protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			}
			
		}
	 private InputStream AmbilArticle(String URL) {
		 InputStream isi = null ;
		 HttpClient klien = new DefaultHttpClient();
		 HttpGet kirim = new HttpGet(URL);
		 try {
			 HttpResponse respon = klien.execute(kirim);
			 isi = respon.getEntity().getContent();
		 }catch (Exception e) {
			 Log.d("Error",e.toString());
		 }
		 return isi ;
	 }
	 private String rubahKeString (InputStream isi) {
		 BufferedReader rd = new BufferedReader(new InputStreamReader(isi), 4096);
		 String baris ;
		 StringBuilder sb = new StringBuilder();
		 try {
			 while ((baris=rd.readLine())!=null){
				 sb.append(baris);
			 }
			 rd.close();
		 }catch (Exception e) {
			 Log.d("Error String",e.toString()) ;
		 }
		 String article=sb.toString();
		 return article;
	 }
	 
	        
}

